package com.zlp.sentinel.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.zlp.sentinel.feign.StockFeign;
import com.zlp.sentinel.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
@Slf4j(topic = "OrderServiceImpl")
public class OrderServiceImpl implements OrderService {


    @Resource
    StockFeign stockFeign;


    @Override
    @SentinelResource(value = "sayHello",blockHandler="exceptionHandler",fallback = "helloFallback")
    public String sayHello(String name) {

        return "Hello, " + name;
    }

    @Override
    public String addOrder(int orderId)  {

        String reduct = stockFeign.reduct(orderId);
        return reduct;
    }

    @Override
    @SentinelResource(value="getUser",blockHandler = "blockHandlerGetUser")
    public String getUser() {
        return "查询用户";
    }

    public String blockHandlerGetUser(BlockException e) {
        return "流控用户";
    }



    // Fallback 函数，函数签名与原函数一致或加一个 Throwable 类型的参数.
    public String helloFallback(String name) {

        log.info(String.format("Halooooo %s", name));
        return String.format("helloFallback %s", name);
    }


    /**
     * Block 异常处理函数，参数最后多一个 BlockException，其余与原函数一致.
     * @param name
     * @param ex
     * @date: 2021/11/12 9:08
     * @return: java.lang.String
     */
    public String exceptionHandler(String name, BlockException ex) {
        // Do some log here.
        ex.printStackTrace();
        log.info("exceptionHandler.req  " + name);
        return "异常处理函数 " + name;
    }
}
